import React from 'react';
import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import axios from "@iso/http";
import Card from "@iso/containers/UIElements/Card/Card.styles";
import {Fieldset, Form, Label} from "@iso/containers/FirestoreCRUD/Article/Article.styles";
import Input from '@iso/components/uielements/input';
import Qs from 'qs'
import PageHeader from '@iso/components/utility/pageHeader';
import {Spin, Tree} from "antd";
import {DownOutlined} from "@ant-design/icons";
import CkEditor from "@iso/components/Editor/CkEditor";
import {withRouter} from "react-router";
import {convertData} from "./CategoryTreeDataUtils";
import Switch from '@iso/components/uielements/switch';
import {showErrorMessage, showSuccessMessage} from "@iso/containers/Feedback/Message/MessageUtils";
import FileUploadButton from "@iso/containers/Pages/Oa/File/FileUploadButton";


 class NoticeEdit extends React.Component {


    constructor(props) {
        super(props);
        this.state={
            data:[],
            title:'',
            content:'',
            categorySelectedKeys:[],
            autoSave:true,
            spinning:false};
    }


    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };


     loadCategoryData=() =>{
        axios.post('api/core/notice/category/findAll', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let list=data.data

                list=convertData(list,0);

                this.setState({data:list});
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    loadData=() =>{
       axios.post('api/core/notice/getOne', Qs.stringify({
            id:this.props.match.params.id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState(data.data)
                    if(data.data.category!=null){
                        this.setState({categorySelectedKeys:['key_'+data.data.category.id]});
                    }
                }
            })
            .catch(function (error) {
                console.log(error);
            });

    }

    getCategoryId=()=>{
          let categorySelectedKeys=this.state.categorySelectedKeys;
          if(categorySelectedKeys.length==0){
              return null;
          }
          let categorySelectedKey=categorySelectedKeys[0];
          let categoryId=categorySelectedKey.substring(4,categorySelectedKey.length);
          return categoryId;
    }
    update=() =>{
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content,id:this.state.id};
        axios.post('api/core/notice/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    showSuccessMessage(data.message)
                }else{
                    showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                console.log(error);
            });
     }

     autoUpdate=() =>{
         if(this.state.title==''||this.state.content==''){
             return ;
         }
         let categoryId=this.getCategoryId();
         let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content,id:this.state.id};
         axios.post('api/core/notice/update', Qs.stringify({
             requestJson:JSON.stringify(entity)
         }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
             .then((response)=>{
                 let  data=response.data;
                 if(data.status==1){
                     showSuccessMessage('已自动保存！')
                 }else{
                     showErrorMessage(data.message);
                 }
             })
             .catch(function (error) {
                 console.log(error);
             });
     }

    categoryOnSelect = (selectedKeys, info) => {
        this.setState({categorySelectedKeys:selectedKeys})
    }

   componentDidMount() {
        this.loadCategoryData();
        this.loadData();

       this.timer = setInterval(
           () => {
               if(this.state.autoSave==true){
                   this.autoUpdate();
               }
           },
           10000
       );
   }

     upload=(fileContentList)=>{
         let entity={fileContentList:fileContentList,
             currentDirectory:'notice/'
         }
         this.setState({spinning:true});
         axios.post('api/objectStore/file/upload', Qs.stringify({
             requestJson:JSON.stringify(entity)
         }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
             .then((response)=>{
                 this.setState({spinning:false});
                 let  data=response.data;
                 if(data.status==1){

                     let dataList=data.data;

                     let fileLinkHtml='';

                     for(let i=0;i<dataList.length;i++){

                         let dataItem=dataList[i];

                         fileLinkHtml=fileLinkHtml+'<p><a href="'+dataItem+'" target="_blank">'+fileContentList[i].name+'</p>';
                     }

                     let newContent=this.state.content+fileLinkHtml;

                     this.setState({content:newContent})

                 }else{
                     showErrorMessage(data.message);
                 }
             })
             .catch(function (error) {
                 showErrorMessage(error);
                 this.setState({spinning:false});
             });
     }

     componentWillUnmount() {
         this.timer && clearTimeout(this.timer);
     }

    render() {
    return (
        <Spin spinning={this.state.spinning} >
      <LayoutContentWrapper >
          <PageHeader>
              编辑通知
          </PageHeader>
        <LayoutContent>


            <Card
                title=''
                style={{ width: '100%' }}
            >

                <Form >
                    <Fieldset>
                        <Label>自动保存:</Label>
                        <Switch checked={this.state.autoSave}  onChange={()=>{

                            if(this.state.autoSave==true){
                                this.setState({autoSave:false})
                            }else {
                                this.setState({autoSave:true})
                            }
                        }
                        }/>
                    </Fieldset>
                    <Fieldset>
                        <Label>标题:</Label>
                        <Input
                            label="标题"
                            placeholder="标题"
                            value={this.state.title}
                            onChange={e => this.onRecordChange(e, 'title')}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>分类:</Label>
                        <Tree
                            switcherIcon={<DownOutlined />}
                            onSelect={this.categoryOnSelect}
                            selectedKeys={this.state.categorySelectedKeys}
                            treeData={this.state.data}
                        />
                    </Fieldset>
                    <Fieldset>
                        <Label>附件:</Label>
                        <FileUploadButton config={{
                            id:'upload-button-1',
                            accept: [".png", ".jpg",".zip",".pdf",".mp3",".mp4"],
                        }} onChange={this.upload}/>
                    </Fieldset>
                    <Fieldset>
                        <Label>内容:</Label>
                        <CkEditor handleChange={(data)=>{this.setState({content:data})}} data={this.state.content} />
                    </Fieldset>


                </Form>


            </Card>

        </LayoutContent>
      </LayoutContentWrapper>
        </Spin>
    );
  }
}
// this wrapper is for fixing bug that we can not get this.props.location
export default withRouter(NoticeEdit)
